﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Objects;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace WorldBankBBS.Data
{
    public partial class Thread
    {
        public int GetUnreadMessagesForUser(Guid userUID)
        {
            bool needSave = false;
            using (var mh = new ModelHelper())
            {
                mh.BeginNewContext();

                var result = (from m in mh.Context.MessageUsers.Where(x => x.UserUID == userUID)
                              where !m.IsRead && m.Message.ThreadUID == ThreadUID
                              select m).ToList().Count();

                foreach (
                    var message in
                        Messages.Where(m => m.MessageUsers.FirstOrDefault(x => x.UserUID == userUID) == null)
                    )
                {
                    ++result;

                    var mu = new MessageUser
                    {
                        IsHidden = false,
                        IsRead = false,
                        MessageUID = message.MessageUID,
                        UserUID = userUID,
                    };

                    mh.Context.MessageUsers.Add(mu);

                    needSave = true;
                }


                if (needSave) mh.Context.SaveChanges();

                return result;
            }

            return 0;
        }

        public static Thread GetFromThreadUID(Guid guid)
        {
            using (var mh = new ModelHelper())
            {
                mh.BeginNewContext();

                return mh.Context.Threads.FirstOrDefault(x => x.ThreadUID == guid);
            }
        }
    }
}
